﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Artech.PetShop.Orders.BusinessEntity;
using Artech.PetShop.Common;
using System.Data.Common;
using System.Data;

namespace Artech.PetShop.Orders.DataAccess
{
    public class ProductDA: DataAccessBase
    {       
        public Product[] GetAllProducts()
        {           
            List<Product> products = new List<Product>();
            using (DbDataReader reader = this.Helper.ExecuteReader("P_PRODUCT_GET_ALL", new Dictionary<string, object>()))
            {
                while (reader.Read())
                {
                    products.Add(new Product
                    {
                        ProductID   = new Guid((string)reader["PRODUCT_ID"]),
                        ProductName = (string)reader["PRODUCT_NAME"],
                        Description = (string)reader["PRODUCT_DESC"],
                        Picture     = (string)reader["PRODUCT_PIC"],
                        UnitPrice   = (decimal)reader["PRODUCT_UNIT_PRICE"],
                        Category    = (string)reader["PRODUCT_CATEGORY"],
                        Inventory   = (int)reader["PRODUCT_INVENTORY"]
                    });
                }
            }

            return products.ToArray<Product>();
        }

        public Product GetProductByID(Guid productID)
        {
            Dictionary<string, object> parameters = new Dictionary<string, object>();
            parameters.Add("p_product_id", productID.ToString());
            using (DbDataReader reader = this.Helper.ExecuteReader("P_PRODUCT_GET_BY_ID", parameters))
            {
                while (reader.Read())
                {
                    return new Product
                    {
                        ProductID   = new Guid((string)reader["PRODUCT_ID"]),
                        ProductName = (string)reader["PRODUCT_NAME"],
                        Description = (string)reader["PRODUCT_DESC"],
                        Picture     = (string)reader["PRODUCT_PIC"],
                        UnitPrice   = (decimal)reader["PRODUCT_UNIT_PRICE"],
                        Category = (string)reader["PRODUCT_CATEGORY"],
                        Inventory = (int)reader["PRODUCT_INVENTORY"]
                    };
                }
            }

            throw new BusinessException(string.Format("The product ID \"{0}\" doese not exist.", productID));
        }
    }
}